package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.CheckItemDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private CheckItemDao checkItemDao;
    @Autowired
    private FreeMarkerConfig freeMarkerConfig;
    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        this.setSetmealAndCheckGroupId(setmealId, checkgroupIds);
        Jedis jedis = jedisPool.getResource();
        jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        jedis.close();
        generateMobileStaticHtml();
    }

    public void generateMobileStaticHtml() {
        List<Setmeal> setmealList = setmealDao.findAll();
        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);

        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(setmealList);
    }

    //需要生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map map = new HashMap();
        map.put("setmealList", setmealList);
        generteHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    //需要生成套餐详情静态页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {

        for (Setmeal setmeal : setmealList) {
            Map map = new HashMap();
            Setmeal byId = findById(setmeal.getId());
            map.put("setmeal", byId);
            generteHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }

    }

    //生成静态页面通用方法
    public void generteHtml(String templateName, String htmlPageName, Map map) {
        Configuration configuration = freeMarkerConfig.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outPutPath + "/" + htmlPageName)), "UTF-8"));
            //输出
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //分页
        PageHelper.startPage(currentPage, pageSize);

        //条件查询
        Page<Setmeal> page = setmealDao.selectByCondition(queryString);

        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public List<Setmeal> findAll() {
        List<Setmeal> list = setmealDao.findAll();
        return list;
    }

    /**
     * 根据id查询套餐详情页面
     *
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        List<CheckGroup> checkGroupList = checkGroupDao.findCheckGroupBySetmealId(id);
        if (checkGroupList != null && checkGroupList.size() > 0) {
            for (CheckGroup checkGroup : checkGroupList) {
                Integer checkGroupId = checkGroup.getId();
                List<CheckItem> checkItemList = checkItemDao.findCheckitemByCheckgroupId(checkGroupId);
                checkGroup.setCheckItems(checkItemList);
            }

        }
        setmeal.setCheckGroups(checkGroupList);
        return setmeal;
    }

    /**
     * 根据id查询套餐
     *
     * @param id
     * @return
     */
    @Override
    public Setmeal findBySetmealId(Integer id) {

        return setmealDao.findById(id);
    }

    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer id) {
        return setmealDao.findCheckGroupIdsBySetmealId(id);
    }

    @Override
    public void edit(Integer[] checkgroupIds, Setmeal setmeal) {
        setmealDao.edit(setmeal);//编辑套餐
        setmealDao.deleteConnection(setmeal.getId());//删除中间表关系
        setSetmealAndCheckGroupId(setmeal.getId(), checkgroupIds);//添加中间表关系

        Jedis jedis = jedisPool.getResource();
        jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        jedis.close();
        generateMobileStaticHtml();
    }

    @Override
    public void deleteConnection(Integer id) {
        setmealDao.deleteConnection(id);
    }

    @Override
    public void delete(Integer id) {
        setmealDao.delete(id);
    }

    /**
     * 把添加中间表关联抽成方法
     *
     * @param setmealId
     * @param checkgroupIds
     */
    public void setSetmealAndCheckGroupId(Integer setmealId, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setmealDao.setSetmealAndCheckGroupId(map);
            }
        }
    }
}
